<template>
  <px-dialog v-model="visible" title="题目分类管理" @close="cancel">
    <div class="table-top" style="margin-bottom: 8px">
      <px-button type="primary" @click="handleAdd">新增</px-button>
    </div>
    <div v-loading="loading" class="table-content">
      <px-table height="500px" :data="tableData" size="small" border class="common-table">
        <px-table-column prop="name" label="分类名称" min-width="120" show-overflow-tooltip />
        <px-table-column prop="sort" label="排序" min-width="120" show-overflow-tooltip />
        <px-table-column prop="updateTime" label="更新时间" min-width="120" show-overflow-tooltip />
        <px-table-column prop="updateByName" label="更新人" min-width="120" show-overflow-tooltip />
        <px-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="scope">
            <px-tooltip content="编辑" placement="top">
              <px-button link icon="EditPen" type="primary" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip content="删除" placement="top">
              <px-button link icon="Delete" type="primary" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        class="table-pagination"
        :total="total"
        @pagination="handleQuery"
      />

      <!-- 新增/编辑 -->
      <px-dialog v-model="editDialogVisible" :title="formTitle" width="400" @close="cancelEdit">
        <px-form ref="formRef" :model="editFormParams" :rules="rules">
          <px-form-item label="分类名称" prop="name" label-width="80">
            <px-input v-model="editFormParams.name" placeholder="请输入" maxlength="20" clearable style="width: 260px" />
          </px-form-item>
          <px-form-item label="序号" prop="idx" label-width="80">
            <px-input-number v-model="editFormParams.idx" :min="0" placeholder="请输入" step-strictly clearable style="width: 260px" />
          </px-form-item>
        </px-form>
        <template #footer>
          <span class="dialog-footer">
            <px-button @click="cancelEdit">取消</px-button>
            <px-button type="primary" @click="saveEdit">确定</px-button>
          </span>
        </template>
      </px-dialog>
    </div>
  </px-dialog>
</template>

<script setup>
import { computed, ref, reactive, toRefs, onMounted } from "vue";
import { getQuestionCategoryListAPI, saveQuestionCategoryListAPI, deleteQuestionCategoryListAPI } from "@/api/knowledge/examManage";
import { PxMessage, PxMessageBox } from "px-ui";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});
const emits = defineEmits(["update:visible", "refresh"]);

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});

const formRef = ref(null);

const rules = computed(() => ({
  name: [{ required: true, message: "分类名称不能为空", trigger: "blur" }],
  idx: [{ required: true, message: "序号不能为空", trigger: "blur" }]
}));

const state = reactive({
  loading: false,
  tableData: [],
  total: 1,
  pageNum: 1,
  pageSize: 20,
  editDialogVisible: false,
  editFormParams: {},
  formTitle: "",
  rowData: {}
});
const { loading, tableData, total, pageNum, pageSize, editDialogVisible, editFormParams, formTitle, rowData } = toRefs(state);

onMounted(() => {
  handleQuery();
});

// 获取分类列表
const handleQuery = async () => {
  try {
    state.loading = true;
    const params = {
      size: state.pageSize,
      current: state.pageNum,
      name: ""
    };
    const res = await getQuestionCategoryListAPI(params);
    state.tableData = res.records;
    state.total = res.total;
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

const handleAdd = () => {
  state.formTitle = "新增题目分类";
  state.editDialogVisible = true;
  state.rowData = {};
};

const handleEdit = row => {
  state.formTitle = "编辑题目分类";
  state.editFormParams.name = row.name;
  state.editFormParams.idx = row.sort;
  state.rowData = row;
  state.editDialogVisible = true;
};

const handleDelete = async row => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      await deleteQuestionCategoryListAPI({ categoryId: row.categoryId });
      PxMessage.success("删除成功");
      handleQuery();
    })
    .catch(() => {});
};

const cancel = () => {
  emits("update:visible", false);
  emits("refresh");
};

const cancelEdit = () => {
  formRef.value.resetFields();
  state.editDialogVisible = false;
};

const saveEdit = () => {
  formRef.value?.validate(async validate => {
    if (validate) {
      const params = {
        categoryId: state.formTitle.includes("新增") ? null : state.rowData.categoryId,
        category: state.editFormParams.name,
        sort: state.editFormParams.idx
      };
      const res = await saveQuestionCategoryListAPI(params);
      cancelEdit();
      handleQuery();
      PxMessage.success(state.formTitle.includes("新增") ? "新增成功" : "编辑成功");
    }
  });
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/knowledge/examManage/scss/common.scss");
</style>
